import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Web3 from 'web3';
import { Input, Button, Typography } from 'antd';
import UserListABI from '../contract/ABIs/UserList.json';
import MarketplaceABI from '../contract/ABIs/Marketplace.json';
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr';
import UserListAddr from '../contract/ADDRESSes/UserListAddr';
import '../styles.css';

const Login = () => {
    const web3 = new Web3(window.ethereum);
    const navigate = useNavigate();
    const [address, setAddress] = useState('');
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [ContractUserList, setContractUserList] = useState(null);
    const [ContractMaterial, setContractMaterial] = useState(null);
    const [userContractAddr, setuserContractAddr] = useState(null);

    useEffect(() => {
        const init = async () => { // 将异步函数声明移到内部
            if (window.ethereum) {
                try {
                    await window.ethereum.enable();
                    // web3 实例化完成后再创建合约实例
                    const UserListInstance = new web3.eth.Contract(UserListABI, UserListAddr);
                    setContractUserList(UserListInstance);

                    const MaterialListInstance = new web3.eth.Contract(MarketplaceABI, MaterialListAddr);
                    setContractMaterial(MaterialListInstance);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        };

        init(); // 调用异步函数
    }, []);

    const handleLogin = async () => {
        if (!web3 || !ContractUserList) { // 检查 web3 和 ContractUserList 是否已实例化
            console.error("Web3 或合约实例未初始化");
            return;
        }

        try {
            const accounts = await web3.eth.getAccounts();
            const currentAddress = accounts[0];
            setAddress(currentAddress);

            const isPasswordValid = await ContractUserList.methods.verifyPwd(username, password).call({ from: currentAddress });

            if (isPasswordValid) {
                localStorage.setItem('address', currentAddress);
                localStorage.setItem('username', username);

                const userContractAddr = await ContractUserList.methods.users(currentAddress).call({ from: currentAddress });
                setuserContractAddr(userContractAddr);
                navigate(`/index1/${userContractAddr}/AddProduct`);
            } else {
                alert('密码错误!');
            }
        } catch (error) {
            console.error('登录失败:', error);
        }
    };

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            // height: '300px', // 移除高度限制
            height: '100vh', // 使用 vh 单位
            backgroundColor: 'lightblue'
        }}
            className="container">
            <div className="header">
                <Typography.Title level={2} style={{ color: '#772F91' }}>先锋校园二手交易平台</Typography.Title>
                <Typography.Title level={3} style={{ color: '#772F91' }}>登录</Typography.Title>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '300px' }}>
                <Input
                    placeholder="用户名"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    className="input-field"
                    style={{ width: '300px', marginBottom: '10px' }}
                />
                <Input.Password
                    placeholder="密码"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="input-field"
                    style={{ width: '300px', marginBottom: '20px' }}
                />
                <Button type="primary" onClick={handleLogin} className="button-primary" style={{ width: '300px' }}>
                    登录
                </Button>
            </div>
        </div>
    );
};
export default Login;
